<template>
  <div class="work-detail">
    <!-- 标题区 + 工具栏 -->
    <div class="load-mask" v-loading="load">
      <el-scrollbar v-if="arr_empty" id="work_area" ref="ElScroll" style="width:100%" max-height="100%">
        <div class="swiper-slide">
          <el-row :gutter="12" justify="start" id="scrollview">
            <transition-group name="list" tag="div">
              <el-col :span="12" v-for="item in main_content.list" :key="item">
                <el-card shadow="hover" class="list-margin-bottom list-margin-top">
                  <el-descriptions :column="col" border>
                    <template #title>
                      <div style="
                        height: 40px;
                        width: 100%;
                        position: relative;
                        overflow: hidden;
                      ">
                        <el-text line-clamp="2" v-html="hightlightlink(item.name)"></el-text>
                      </div>
                    </template>
                    <el-descriptions-item label="创建人">{{
                      item.creator ? item.creator.name : ""
                    }}</el-descriptions-item>
                    <el-descriptions-item label="优先级">
                      <el-text :type="(item.priority === 2) ? 'warning' : (item.priority === 3) ? 'danger' : 'default'">
                        {{ find_object_val(priority_options, 'value', item.priority)['label'] }}
                      </el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="指派给">
                      <el-space>
                        <el-tag :disable-transitions="true" v-if="item.assign && item.assign.length > 0"
                          v-for="it in item.assign" :key="it">{{ it }}</el-tag>
                        <el-tag :disable-transitions="true" v-else type="error">
                          暂无
                        </el-tag>
                      </el-space>
                    </el-descriptions-item>
                    <el-descriptions-item label="工作量">
                      <el-text type="success" v-if="!edit_visiblle.workload" @dblclick="edit_visiblle.workload = true">
                        {{ item.workload }}
                      </el-text>
                      <el-input style="width: 120px" type="number" tabindex="1" :autofocus="true" v-else
                        @blur="edit_visiblle.workload = false" v-model="clone_form.workload"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="任务归属">{{
                      item.revert
                    }}</el-descriptions-item>
                    <el-descriptions-item label="状态">
                      <el-select :disabled="item.status.value === 5" tag-type="success" @focus="load_options"
                        v-model="item.status" placeholder="任务状态" style="width: 170px">
                        <el-option v-for="item in status_option.options" :key="item.value" :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">
                      {{ _Time(item.create_datetime) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="开始时间">
                      <el-date-picker v-model="item.start_time" type="date" unlink-panels />
                    </el-descriptions-item>
                    <el-descriptions-item label="完成时间">
                      <el-space>
                        <el-date-picker v-model="item.end_time" type="date" unlink-panels />
                        <el-tag disable-transitions="false" type="danger" size="large" v-if="item.is_expire"
                          effect="dark">
                          <span class="stand-font-size">延期</span>
                        </el-tag>
                      </el-space>
                    </el-descriptions-item>
                    <el-descriptions-item label="最近更新时间">
                      <el-text> {{ _Time(item.modify_time) }} </el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="描述" label-position="top" span="2" rowspan="1">
                      <div class="descript">
                        <el-row flex justify="left">
                          <el-col :span="2">
                            <el-button @click="edit_content(item)" type="info" link text>
                              <el-icon>
                                <Edit />
                              </el-icon>
                              编辑
                            </el-button>
                          </el-col>
                        </el-row>
                        <el-row>
                          <e-col v-if="item.rich_content && item.rich_content.code === 200" :span="24"
                            class="rich_content-item">
                            <div v-html="item.rich_content.content" class="w-e-text-container"></div>
                          </e-col>
                          <e-col v-else :span="24" class="stand-font-size">
                            暂无描述
                          </e-col>
                        </el-row>
                      </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="关联子单" span="2" rowspan="1">
                      <!-- 子单列表 -->
                      <el-button @click="add_project_child(item)" type="primary" round size="normal"
                        icon="plus"></el-button>
                      <div v-if="item && item.child_list" class="child-list-container">
                        <el-tree-v2 :data="item.child_list" :height="140" @node-click="treeClick"
                          :props="{ value: 'list_id', label: 'name', children: 'children' }"></el-tree-v2>
                      </div>
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </el-col>
            </transition-group>
          </el-row>
        </div>
      </el-scrollbar>
      <el-empty v-else description="暂无数据" v-loading="load"></el-empty>
    </div>
    <Project v-if="project_form.visible" @success="refresh(null)" v-model:visible="project_form.visible"></Project>
    <!-- 添加二级单子 -->
    <el-dialog :show-close="true" v-loading="child_load" direction="ttb" :destroy-on-close="true" size="100%"
      v-model="child_visible" title="添加子单">
      <el-form v-model="child_data" label-width="auto">
        <el-form-item label="主题" prop="name">
          <el-input placeholder="主题内容" style="width:80%" v-model="child_data.name"></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="child_data.priority" style="width: 140px">
            <el-option v-for="item in priority_options" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select tag-type="success" @focus="load_options" v-model="child_data.status" placeholder="任务状态"
            style="width: 170px">
            <el-option v-for="a in status_option.options" :key="a.value" :label="a.label" :value="a.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="指派给" prop="ssign_id">
          <el-select v-model="child_data.assign_id" style="width: 240px" filterable remote reserve-keyword
            :remote-method="fetch_users" clearable loading-text="搜索中..." :loading="child_data_option.user_load"
            placeholder="请输入关键字搜索，支持拼音检索">
            <el-option v-for="item in child_data_option.user_options" :key="item.id" :label="item.name"
              :value="item.account">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作量（人/天）" prop="workload">
          <el-input-number :min="0" :step="0.1" control v-model="child_data.workload" />
        </el-form-item>
        <el-form-item label="归属版本" prop="revert">
          <el-input v-model="child_data.revert" placeholder="请输入归属版本" style="width: 240px" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker v-model="child_data.start_time" type="date" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker v-model="child_data.end_time" type="date" placeholder="请选择结束时间" />
        </el-form-item>
        <el-form-item label="需求类型" prop="type">
          <el-select v-model="child_data.type" style="width: 240px" filterable remote reserve-keyword
            :remote-method="fetch_work_type" clearable loading-text="搜索中..." placeholder="请输入关键字搜索，支持拼音检索">
            <el-option v-for="item in child_data_option.work_type" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 拼接单联调 -->
        <el-form-item label="联调时间" prop="end_time" v-if="child_data.type === 5">
          <el-date-picker v-model="child_data.debug_time" type="date" placeholder="请选择结束时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-space wrap>
          <el-button type="danger" @click="child_visible = false"> 取消</el-button>
          <el-button type="primary" @click="submit_child">确认</el-button>
        </el-space>
      </template>
    </el-dialog>
    <!-- 富文本编辑器弹窗 -->
    <el-dialog :destroy-on-close="true" :before-close="beforeClose" :fullscreen="false" v-model="rich_visible"
      v-loading="rich_load" title="描述">
      <Editor v-model:value="rich_data" @complete="rich_submit" />
    </el-dialog>
    <div class="bottom_mask">
      <el-row style="width: 100%;" flex justify="space-between">
        <el-col :span="2">
          <el-space>
            <el-button type="primary" @click="add_project">
              <template #icon>
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
              添加总单</el-button>
            <el-button text type="primary" @click="refresh">
              <template #icon>
                <el-icon :size="18">
                  <RefreshLeft />
                </el-icon>
              </template>
            </el-button>
          </el-space>
        </el-col>
        <el-col :span="2">
          <el-pagination background @current-change="page_chage" :page-count="Math.ceil(all / 12)"
            layout="prev, pager, next" :total="all" v-model:current-page="page" />
        </el-col>
        <el-col :span="4">
          <el-button text @click="scroll_top" v-if="arr_empty" icon="arrow-up-bold"></el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import Editor from "@/components/rich_text/index.vue";
import { isProxy, defineComponent, ref, watch, onMounted, reactive, computed, toRaw } from "vue";
import { useRoute, useRouter } from "vue-router";
import Window from "@/components/project_window/index.vue";
import {
  str_utils,
  get as http_get,
  post as http_post,
  URL,
  TimeFormatter,
  obj_empty,
  priority_options,
  counter,
  find_object_val,
  post_form
} from "@/tool/common";
import { ElMessage } from "element-plus";
import { debounce } from "@/tool/screen";
const de = debounce();
export default defineComponent({
  name: "Custom",
  components: {
    Project: Window,
    Editor
  },
  setup: () => {
    // 富文本编辑模式
    const rich_data = ref();
    const self_id = ref(null);
    const rich_visible = ref(false);
    const rich_load = ref(false);
    const child_visible = ref(false);
    const load = ref(false);
    const child_load = ref(false);
    // 滚动容器
    const ElScroll = ref(null);
    // 表单
    const edit_visiblle = reactive({
      workload: false,
    });
    let clone_form = ref();
    // 克隆数据
    const route = useRoute();
    const router = useRouter();
    const main_content = reactive({
      list: [],
    });
    const status_option = ref({
      options: null,
      value: null,
    });
    // 子单数据 -----------------需要删除默认数据
    const child_data = reactive({
      name: "#381615 【第七季资料片】资料片入口-主入口+玩法展示界面-登入请帖引导修改-GUI拼接",// null, //主题名字
      parent_id: null, // 上一级id 根据当前文件夹创建
      workload: 5,//null, // 工作量
      self_id: null, // 自身id 自动分配
      create_datetime: null, // 创建时间 自动
      start_time: "2024-11-26",// null, // 排期开始时间 
      end_time: "2024-12-12",// null, // 结束完成时间
      modify_time: null, // 修改时间 系统自动记录
      status: 0,// null, // 需求状态
      priority: 0,// null, // 优先级
      revert: "第七季",// null, // 归属资料片
      author_id: null, // 创建者id
      children_id: null, // 子单id
      user_id: null,// 指派id
      of_id: null, // 归属id
      remark: null, // 备注
      debug_time: null, // 联调时间
      assign_id: null, // 指派id
      type: null // 需求类型
    });
    const child_data_option = ref({
      user_options: [],
      user_load: false,
      work_type: null
    });
    const all = ref(0); //; 该目录下包含的单子数量 作分页
    // 添加父级单
    const project_form = reactive({
      visible: false,
      data: {},
    });
    const col = ref(2);
    let is_end = ref(false);
    const page = ref(1);
    const is_show_debug_time = ref(false);
    function load_options() {
      if (status_option.value.options) {
        return;
      }
      http_get({
        url: URL.BASE + URL.API_STATUS_OPTIONS,
      }).then((res) => {
        status_option.value.options = res;
      });
    }
    watch(route, (n) => {
      refresh(n);
    });
    // 刷新数据
    function refresh(n) {
      load.value = true;
      main_content.list = [];
      de.run(() => {
        page.value = 1;
        is_end.value = false;
        req_detail((n && isProxy(n)) ? n.query.id : route.query.id);
      }, 540);
    }
    onMounted(() => {
      load_options();
      refresh(route);
      let body_width = window.innerWidth / window.devicePixelRatio;
      col.value = body_width > 700 ? 2 : 1;
      window.addEventListener(
        "resize",
        () => {
          de.run(() => {
            body_width = document.body.clientWidth;
            col.value = body_width > 840 ? 2 : 1;
          }, 480);
        },
        {
          passive: true,
          onece: true,
        }
      );
    });
    // 监控具体字段是要写成函数式 返回值
    watch(() => child_data.type, (n) => {
      if (n !== 5) {
        // 清空联调时间，设置为null
        child_data.debug_time = null;
      }
    });
    const arr_empty = computed(() => {
      return main_content.list != null && main_content.list.length !== 0;
    });
    function beforeJump(e) {
      e.preventDefault();
      return false;
    }
    function hightlightlink(str) {
      if (str_utils.is_empty(str)) {
        return str;
      }
      const res = str.match(/#\d{1,6}/g);
      const _str = str.replace(/#\d{1,6}/g, "");
      if (res) {
        return `<span> <a target="_blank" class='hight-light-link' href='https://g66.pm.netease.com/v6/issues/${res[0]}'> ${res[0]} <a/> ${_str} </span>`;
      } else {
        return str;
      }
    }
    // 加载排期单
    function req_detail(id, call) {
      if (is_end.value) {
        return;
      }
      if (!str_utils.is_empty(id)) {
        http_get({
          url:
            URL.BASE + URL.API_PARENT_QUERY + "?id=" + id + "&page=" + (page.value - 1),
        })
          .then((res) => {
            if (res && res.total > 0) {
              all.value = res.all;
              let __list = res.list;
              if (__list.length <= 0) {
                is_end.value = true;
              } else {
                main_content.list = __list;
                let clone = _.clone(__list[0]);
                clone_form.value = clone;
              }
            } else {
              main_content.list = [];
            }
            if (typeof call === "function") {
              call();
            }
          })
          .catch((err) => {
            void err;
          })
          .finally(() => (load.value = false));
      }
    }

    function _Time(d) {
      if (!d) {
        return;
      }
      let _formtter = TimeFormatter(d);
      return _formtter.get_date("-", "-") + " " + _formtter.get_time();
    }
    // 添加一级内容
    function add_project() {
      project_form.visible = true;
    }
    // 添加二级内容
    function add_project_child(prop = null) {
      let id = prop.self_id || null;
      if (!obj_empty(prop) && str_utils.not_empty(prop.self_id)) {
        child_data.parent_id = id; // 设置父单子id
        child_visible.value = true;
      } else {
        ElMessage.warning({
          message: "非法参数",
        });
      }
    }

    function scroll_top() {
      if (!ElScroll.value || arr_empty.value === false) {
        return
      }
      let start = ElScroll.value.wrapRef.scrollTop;
      counter(start, -10, 4.31, (val) => {
        ElScroll.value.setScrollTop(val);
      });
    }

    function page_chage(index) {
      page.value = index;
      req_detail(route.query.id, scroll_top);
    }

    function fetch_users(word) {
      child_data_option.value.user_load = true;
      if (str_utils.not_empty(word)) {
        http_post({
          url: URL.BASE + URL.API_USER_SEARCH,
          data: {
            keyword: word,
          },
        })
          .then((res) => {
            child_data_option.value.user_options = res || [];
            child_data_option.value.user_load = false;
          })
          .catch((err) => console.error(err));
      }
    }
    // 富文本提交
    function rich_submit(ev) {
      let content = ev;
      rich_load.value = true;
      let id = self_id.value;
      if (str_utils.not_empty(content)) {
        let formData = new FormData();
        formData.append("list_id", id);
        formData.append("content", content);
        post_form({
          url: URL.BASE + URL.API_UPLOAD_RICH_CONTENT,
          formData
        }).then(res => {
          if (res && res.code === 200) {
            rich_visible.value = false;
            rich_load.value = true;
            refresh();
          }
        }).catch(err => {
          console.log(err)
        })
      }
    }
    // 编辑富文本
    function edit_content(item) {
      if (!item) { return; }
      rich_visible.value = true; self_id.value = item.self_id;
      let _ = toRaw(item.rich_content);
      let _value = (_ && _.code === 200) ? _.content : null;
      rich_data.value = _value;
    }
    function fetch_work_type() {
      if (child_data_option.value.work_type === null)
        http_post({
          url: URL.BASE + URL.API_TYPE_OPTIONS
        }).then(res => {
          if (res) {
            child_data_option.value.work_type = res.list
          } else {
            child_data_option.value.work_type = null
          }
        }).catch(() => {
          child_data_option.value.work_type = null
        })
    }
    function submit_child() {
      const data = toRaw(child_data);
      // 需要添加一个loading
      child_load.value = true;
      http_post({
        url: URL.BASE + URL.API_CHILD_PUSH,
        data: {
          token: Cookies.get("token"),
          param: data
        }
      }).then((res) => {
        if (res && res.code === 200) {
          ElMessage({
            message: "添加成功",
            type: "success",
            duration: 2300,
            onClose() {
              child_load.value = false;
              child_visible.value = false;
            }
          });
        } else {
          ElMessage.warning(res.msg ?? '未定义错误');
        }
      }).catch(err => {
        ElMessage.warning(err ?? '未定义错误');
      })
    }
    function treeClick(handle) {
      if (handle && str_utils.not_empty(handle.list_id)) {
        let id = handle.list_id.replaceAll("#", "");
        if (str_utils.not_empty(id)) {
          router.push({
            path: "children/detail",
            query: {
              id,
            }
          })
        } else {
          console.error("单号不存在");
        }
      }
    }
    // 编辑富文本关闭后钩子
    function beforeClose(done) {
      ElMessageBox.confirm('确认要关闭当前正在编辑的内容，这样会导致内容丢失哦')
        .then(() => {
          done()
        })
        .catch(() => {
        })
    }
    return {
      beforeClose,
      treeClick,
      is_show_debug_time,
      submit_child,
      fetch_work_type,
      rich_load,
      edit_content,
      rich_submit,
      rich_visible,
      self_id,
      rich_data,
      scroll_top,
      col,
      fetch_users,
      child_data_option,
      child_data,
      child_visible,
      load,
      ElScroll,
      page,
      page_chage,
      all,
      is_end,
      add_project_child,
      project_form,
      add_project,
      main_content,
      hightlightlink,
      beforeJump,
      status_option,
      load_options,
      _Time,
      obj_empty,
      edit_visiblle,
      clone_form,
      arr_empty,
      refresh,
      priority_options,
      find_object_val
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/common/style/common.scss";

.list-move,
/* 对移动中的元素应用的过渡 */
.list-enter-active {
  transition: all 0.5s ease;
}

.list-leave-active {
  display: none;
  transition: all 0 ease;
  position: absolute;
}

.list-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.list-enter-to {
  opacity: 1;
  transform: translateY(0px);
}

.work-detail {
  width: 100%;
  height: 100%;
  overflow: hidden;

  .child-list-container {
    margin-top: 14px;
    margin-bottom: 0px;
    height: 140px;
  }

  .swiper-slide {
    padding-bottom: 50px;

    .el-row {
      >div {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        width: 100%;
        height: auto;
      }

      .descript {
        height: 250px;
        overflow: hidden;
        box-sizing: border-box;
        position: relative;
      }

      .descript::after {
        content: '';
        display: block;
        width: 100%;
        position: absolute;
        z-index: 1;
        bottom: 0;
        height: 22px;
        background-image: linear-gradient(to top, rgb(255, 255, 255), rgba(255, 255, 255, .5), rgba(255, 255, 255, 0));
      }
    }
  }

  ::v-deep(.hight-light-link) {
    font-weight: 800;
    font-size: 16.5px;
    color: var(--el-color-success);
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  ::v-deep(.list-margin-bottom) {
    margin-bottom: 22px;
  }

  ::v-deep(.list-margin-top) {
    margin-bottom: 12px;
  }

  .tool-box {
    position: absolute;
    min-height: 38px;
    left: 12px;
    box-sizing: border-box;
    @include padding0(4px, 4px, 18px, 8px);
  }

  .bottom_mask {
    position: absolute;
    bottom: 0px;
    z-index: 50;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 54px;
    border: 1px solid rgb(236, 236, 236);
    border-bottom: none;
    backdrop-filter: blur(15px);
    background-image: rgba(255, 255, 255, 0.65);
    text-align: center;
  }

  .load-mask {
    overflow: hidden;
    width: 100%;
    height: 100%;
  }

  .rich_content-item {
    height: 230px;
    width: 100%;
    overflow-y: auto;
    overflow-x: hidden;

    .w-e-text-container {
      height: auto;
    }
  }
}
</style>
